import './index.less'
import React, { Component } from 'react';
import { message, Table, Row, Col } from "antd";
import axios from "../../components/service/request";
class component extends Component {

    state = {
        baseUri: this.props.history.location.pathname,
        data: [],
        pagination: {
            current: 1,
            pageSize: 10,
        },
        loading: false,
        editParam: {
            isModalVisible: false,
            value: null,
            // cancelModal:this,.
        },
        selectedRowKeys: [],
        deleteLoading: false,
        searchFlag: false
    };

    getColumns() {
        return null
    }

    getEditModal() {
        return null;
    }

    getSearchRow() {
        return null;
    }

    getButtonRow() {
        return null;
    }

    componentDidMount() {
        this.reload()
    }

    handleSearchFlag = (flag) => {
        this.setState({
            searchFlag: flag
        })
    }

    handleAdd = () => {
        this.setState({
            editParam: {
                isModalVisible: true,
                value: null,
            },
        })
    }

    edit = record => {
        let param = { isModalVisible: true, value: record }
        this.setState({
            editParam: param
        })
    }

    reload = () => {
        const { pagination } = this.state;
        this.fetch(pagination);
    }

    handleTableChange = (pagination, filters, sorter) => {
        let search = { sortField: sorter.field, sortOrder: sorter.order, ...filters, }
        this.setState({
            pagination: Object.assign(this.state.pagination, search)
        }, () => {
            this.reload();
        })

    };

    //用于关闭modal页面
    cancelModal = () => {
        let param = { isModalVisible: false, value: {} }
        this.setState({
            editParam: param
        })
    }


    fetch = (params = {}) => {
        this.setState({ loading: true });

        const paginationParams = {
            pageNum: params.current, // 移除 || this.state.pagination.current
            pageSize: 10, // 固定为10
            ...params // 其他查询参数
        };

        console.log('请求参数:', paginationParams); // 调试用
        axios.post(this.state.baseUri + '/list', params).then(data => {
            if (data.code === 200) {
                // 处理数据，区分是用户列表还是角色列表
                const processedData = data.data.records.map(record => {
                    // 如果记录中有roles字段，说明是用户数据
                    if (record.roles) {
                        const uniqueRoles = Array.from(new Set(record.roles.map(JSON.stringify)))
                            .map(str => JSON.parse(str));

                        return {
                            ...record,
                            roles: uniqueRoles,
                            // 使用去重后的roles生成roleNames
                            roleNames: Array.from(new Set(uniqueRoles.map(role => role.roleName)))
                        };
                    }
                    // 如果没有roles字段，说明是角色列表数据，直接返回原数据
                    return record;
                });

                this.setState({
                    loading: false,
                    data: processedData,
                    pagination: {
                        current: params.current,
                        pageSize: 10,
                        total: data.data.total,

                        showTotal: (total) => `共 ${total} 条记录`,
                    },
                });
            } else {
                message.error(data.msg)
                this.setState({
                    loading: false,
                    data: [],
                });
            }
        });
    };
    // 处理表格变化（分页、排序、筛选）
    handleTableChange = (pagination, filters, sorter) => {
        console.log('分页变化:', pagination); // 调试用

        const params = {
            current: pagination.current, // 直接使用新的页码
            pageSize: 10, // 固定为10
            sortField: sorter.field,
            sortOrder: sorter.order,
            ...filters,
        };

        this.fetch(params);
    };

    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };

    handleChange = (e) => {
        e.preventDefault()
        let search = { [e.target.name]: e.target.value }
        this.setState({
            pagination: Object.assign(this.state.pagination, search)
        })
    }


    // handleDelete = (param) => {
    //     // 构建请求数据
    //     // const requestData = param.toString(); // 转换为字符串

    //     // 判断当前是用户删除还是角色删除
    //     const isUserDelete = this.state.baseUri.includes('/user');
    //     const deleteUrl = isUserDelete
    //         ? '/admin/user/user/delete'  // 用户删除接口
    //         : '/admin/user/role/delete'; // 角色删除接口

    //     // 根据不同接口使用不同的请求方法
    //     const request = isUserDelete
    //         ? axios.post(deleteUrl, param)
    //         : axios.delete(deleteUrl, {
    //             data: param,
    //             headers: {
    //                 'Content-Type': 'application/json'
    //             }
    //         });

    //     request.then(res => {
    //         if (res.code === 200) {
    //             message.success(res.msg || '删除成功');
    //             this.reload();
    //         } else {
    //             message.error(res.msg || '删除失败');
    //             this.reload();
    //         }
    //     }).catch(err => {
    //         console.error('删除失败:', err);
    //         message.error(err.message || '删除失败，请稍后重试');
    //     });
    // };
    handleDelete = (param) => {
        // 构建请求数据为JSON格式
        const requestData = {
            ids: param
        };

        const isUserDelete = this.state.baseUri.includes('/role');
        const deleteUrl = isUserDelete
            ? '/admin/user/role/delete'
            : '/admin/user/user/delete';

        const request = isUserDelete
            ? axios.delete(deleteUrl, {
                data: requestData,
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            : axios.post(deleteUrl, requestData);

        request.then(res => {
            if (res.code === 200) {
                message.success(res.msg || '删除成功');
                this.reload();
            } else {
                message.error(res.msg || '删除失败');
            }
        }).catch(err => {
            console.error('删除失败:', err);
            message.error(err.message || '删除失败，请稍后重试');
        });
    };

    // 删除单个记录
    delete = value => {
        let ids = [];
        ids.push(value.id.toString());
        this.handleDelete(ids.join(','));
    };

    // 删除选中记录
    deleteSelect = () => {
        let selectedRowKeys = this.state.selectedRowKeys;

        if (selectedRowKeys.length === 0) {
            message.error("请选择要删除的数据！");
            return;
        }

        this.setState({
            deleteLoading: true
        }, () => {
            this.handleDelete(selectedRowKeys.join(','));
            this.setState({
                deleteLoading: false,
                selectedRowKeys: [] // 清空选中项
            });
        });
    };

    render() {
        const { data, pagination, loading, selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <>
                <Row gutter={[8, 12]}>
                    <Col span={24} >
                        {
                            this.getSearchRow()
                        }
                    </Col>
                    <Col span={12} className={'function-left'}>

                    </Col>
                    <Col span={12} className={'function-right'}>
                        {
                            this.getButtonRow()
                        }
                    </Col>

                    <Col span={24}>
                        {
                            this.getColumns() ? <Table
                                rowSelection={rowSelection}
                                columns={this.getColumns()}
                                rowKey={record => record.id}
                                dataSource={data}
                                pagination={{
                                    ...pagination,
                                    pageSize: 10, // 固定为10
                                    showQuickJumper: true, // 显示快速跳转
                                    showTotal: (total) => `共 ${total} 条记录`,
                                }}
                                loading={loading}
                                onChange={this.handleTableChange}
                            /> : ""
                        }
                    </Col>
                </Row>
                {
                    this.getEditModal()
                }
            </>
        );
    }
}

export default component;
